<?php

namespace backend\modules\rbac\controllers;

use backend\modules\base\controllers\BaseController;
use backend\modules\rbac\models\Menu;
use backend\modules\rbac\models\MenuPerm;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;

/**
 * RoleController implements the CRUD actions for Role model.
 */
class RoleController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index','create','view','update','addRole','move','getmenuperm','getuser'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Role models.
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Lists all Role models.
     * @return mixed
     */
    public function actionCreate()
    {
        $post = Yii::$app->request->post();
        $postData = isset($post['data'])?$post['data']:'';
        if(!$postData) {
            $menuPerm = new MenuPerm();
            $roles = $menuPerm->getRoles();
            return $this->render('create',['roles'=>$roles]);
        }

        $menuPerm = new MenuPerm();
        if($menuPerm->createRole($postData['name'],$postData['description'])){
            return  $this->redirect(['create']);
        }
        return json_encode(['code'=>500]);
    }

    /**
     * 通过角色获取用户列表
     * @return string|\yii\web\Response
     */
    public function actionGetuser()
    {
        $post = Yii::$app->request->post();
        $postData = isset($post['data'])?$post['data']:'';
        if($postData) {
            $menuPerm = new MenuPerm();
            $userARRs = $menuPerm->getUserByRole($postData['name']);
            return json_encode(['code'=>200,'data'=>$userARRs]);
        }
        return json_encode(['code'=>500]);
    }
}
